package org.webcamp.questionary.services.impl;

import java.util.List;

import org.webcamp.questionary.dto.Answer;
import org.webcamp.questionary.dto.AnswerIndex;
import org.webcamp.questionary.dto.Question;
import org.webcamp.questionary.dto.Questionary;
import org.webcamp.questionary.dto.Score;
import org.webcamp.questionary.services.ScoreCalculator;

public class PercentileScore implements ScoreCalculator {

	@Override
	public Score evaluate(Questionary questionary, List<List<AnswerIndex>> answers) {
		int correctlyAnsweredQuestions = 0;
		for (int i = 0; i < questionary.getQuestions().size(); i++) {
			Question q = questionary.getQuestions().get(i);
			// calculate number of correct answers
			int correctAnswers = 0;
			for (Answer a : q.getAnswers()) {
				if (a.isCorrect()) {
					correctAnswers++;
				}
			}
			int userCorrectAnswers = 0;
			List<AnswerIndex> userAnswers = answers.get(i);
			for (AnswerIndex ai : userAnswers) {
				if (q.getAnswers().get(ai.getIndex()).isCorrect()) {
					userCorrectAnswers++;
				}
			}
			if (userCorrectAnswers == userAnswers.size() && userCorrectAnswers == correctAnswers) {
				correctlyAnsweredQuestions++;
			}
		}
		int score = 100 * correctlyAnsweredQuestions / questionary.getQuestions().size();
		Score result = new Score();
		result.setValue(score + "%");
		if (score > 90) {
			result.setStyle(Score.SUCCESS);
		} else if (score < 16) {
			result.setStyle(Score.DANGER);
		} else {
			result.setStyle(Score.WARNING);
		}
		return result;
	}

}
